<template>
	<div class="talk">
		<div class="blog">
			<div class="blogTop">
				<h3>{{ bolgInfo.title }}</h3>
			</div>

			<div class="blogMiddle">
				<div style="display: inline-block">
					<el-avatar :size="40" :src="AuthorAvatarUrl" style="margin-bottom: -14px"></el-avatar>
				</div>
				<div class="blogContent" style="display: inline-block">
					<div style="margin-left: 24px">
						{{ bolgInfo.content }}
					</div>
				</div>
			</div>

			<div class="blogBottom">
				<span>{{ bolgInfo.author }} 于 {{ bolgInfo.createTime }} 发布</span>

				<span style="float: right">
					<i
						class="el-icon-star-off"
						:class="blogsIsCollect ? 'activ1' : 'activ2'"
						style="margin-right: 14px"
						@click="giveCollect"
						>收藏
					</i>
					<i
						class="el-icon-trophy"
						style="margin-right: 14px"
						:class="blogsIsLike ? 'activ1' : 'activ2'"
						@click="giveALike"
						>点赞</i
					>
				</span>
			</div>
		</div>

		<div class="comment">
			<div class="comment-header" style="margin-bottom: 20px">
				<el-avatar :size="40" :src="selfAvatarUrl"></el-avatar>

				<el-input
					:placeholder="placeholderText"
					v-model="context"
					class="input"
					type="textarea"
					resize="none"
					:maxlength="contentLength"
					@focus="isShowSecReply(undefined)"
				></el-input>
				<el-button type="primary" style="height: 40px" @click="addComment(articleId, undefined)">{{
					buttonText
				}}</el-button>
			</div>
			<div class="comment-body" v-for="(item, index) in comments" :key="item.id + '' + index" :self="item.avatarUrl">
				<!-- 一级评论 -->
				<div class="first-comment">
					<el-avatar :size="40" :src="item.img"></el-avatar>
					<!-- <img :size="40" :src="item.avatarUrl" /> -->
					<div class="content">
						<!-- 一级评论用户昵称 -->
						<h3>{{ item.userName }}</h3>
						<!-- 一级评论发布时间 -->
						<span>{{ item.createTime }}</span>
						<!-- 一级评论评论内容 -->
						<p>{{ item.content }}</p>
						<!-- 一级评论评论点赞 -->
						<div class="comment-right" style="margin-top: 10px">
							<i class="el-icon-chat-dot-round" @click="isShowSecReply(item.id)">回复</i>
						</div>
						<!-- 回复一级评论 -->
						<div class="reply-comment" v-show="isShowSec === item.id">
							<el-input
								:placeholder="placeholderText"
								class="input"
								v-model.trim="replyContext"
								:maxlength="contentLength"
							></el-input>
							<el-button type="primary" size="mini" class="reply-button" @click="addReplay(item.id)">回复</el-button>
						</div>
						<!-- 次级评论 -->
						<div class="second-comment" v-for="(reply, index) in item.replies" :key="reply.id + '' + index">
							<!-- 次级评论头像,该用户没有头像则显示默认头像 -->
							<el-avatar :size="40" :src="reply.img"></el-avatar>
							<div class="content">
								<!-- 次级评论用户昵称 -->
								<h3>{{ reply.userName }}</h3>
								<!-- 次级评论评论时间 -->
								<span>{{ reply.createTime }}</span>
								<span class="to_reply">{{ reply.userName }}</span>
								回复
								<span class="to_reply">{{ reply.commentUserName }}</span
								>:
								<p>{{ reply.content }}</p>
							</div>
						</div>
					</div>
				</div>
			</div>
			<!-- 暂无评论的空状态 -->
			<el-empty :description="emptyText" v-show="comments.length === 0"></el-empty>
		</div>
	</div>
</template>

<script>
import { mapState } from 'vuex'
import { reqABlogOneList } from '@/api'
import { reqABlogCommentList } from '@/api'
import { reqBlogsIsLike } from '@/api'
import { reqBlogsIsCollect } from '@/api'
import { reqUserInfo } from '@/api'
// import requests from '@/api/mockAjax';
import requests from '@/api/ajax'

export default {
	props: {
		articleId: {
			//评论所属文章 id
			type: String
		},
		emptyText: {
			// 评论为空的时候显示的文字
			type: String,
			default: '期待你的评论！'
		},
		buttonText: {
			// 按钮文字
			type: String,
			default: '评论'
		},
		contentLength: {
			// 评论长度
			type: Number,
			default: 150
		},
		placeholderText: {
			// 默认显示文字
			type: String,
			default: '请输入最多150字的评论...'
		}
	},
	data() {
		return {
			blogId: this.$route.query.id,
			blogsIsLike: false,
			blogsIsCollect: false,
			isRight: true,
			bolgInfo: {},
			bolgComment: [],
			AuthorAvatarUrl: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
			avatarUrl: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
			selfAvatarUrl: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',

			comments: [
				{
					id: '', // 评论id
					createTime: '', //创建日期
					userName: '', //评论人
					userId: '',

					// favour: ['1', '2', '3'], //点赞的用户id
					content: '', //评论内容
					img: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',

					replies: [
						//回复的内容
						{
							id: 'sec0', // 当前此条回复的id
							createTime: '2022.09.01', //创建日期
							commentUserName: '孤城浪人', //回复的对象
							userName: '', //评论人
							userId: '1',
							favour: ['2', '3', '4'],
							img: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
							content: '博主厉害了' //回复的内容
						}
					]
				}
			], // 获取得到的评论
			context: '', // 评论内容
			replyContext: '', //一级评论回复
			isShowSec: '', //是否显示次级回复框
			isClickId: '', //记录点击回复的评论id

			firstIdx: 1,
			secIdx: 1
		}
	},
	created() {},
	methods: {
		// 唤起文件选择
		handleClick() {
			this.$refs.avatar.click()
		},
		dealWithdAvatar(e) {
			const maxSize = 2 * 1024 * 1024
			const file = Array.prototype.slice.call(e.target.files)[0]
		},

		// 帖子收藏
		giveCollect() {
			if (this.userStatus !== '') {
				// console.log('' === 0);
				requests
					.put('/collects/blog/addOrCancel', {
						blogId: this.blogId,
						flag: this.blogsIsCollect
					})
					.then((res) => {
						this.blogsIsCollect = !this.blogsIsCollect
						if (res.code == 1) {
							this.$notify.success(res.data)
						} else {
							this.$notify.error(res.data)
						}
					})
			} else {
				this.$confirm('此操作需要先登录, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				})
					.then(() => {
						this.$router.push('/login')
					})
					.catch(() => {})
			}
		},
		giveALike() {
			if (this.userStatus !== '') {
				requests
					.put('/blogs/like/addOrCancel', {
						blogId: this.blogId,
						flag: this.blogsIsLike
					})
					.then((res) => {
						this.blogsIsLike = !this.blogsIsLike
						if (res.code == 1) {
							this.$notify.success(res.data)
						} else {
							this.$notify.error(res.data)
						}
					})
			} else {
				this.$confirm('此操作需要先登录, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				})
					.then(() => {
						// this.$message({
						//   type: 'success',
						//   message: '删除成功!'
						// });
						this.$router.push('/login')
					})
					.catch(() => {
						// this.$message({
						//   type: 'info',
						//   message: '已取消登录',
						// });
					})
			}
		},
		isShowSecReply(id) {
			if (id) {
				this.isShowSec = id
				if (this.isClickId === this.isShowSec) {
					this.isShowSec = ''
				} else {
					this.isShowSec = id
				}
				this.isClickId = this.isShowSec
			} else {
				this.isShowSec = this.isClickId = ''
			}
		},
		deleteComment(id, replyId) {
			if (replyId) {
				// 删除二级评论，提交请求到后端

				// 成功后从本地记录中删除该评论
				const temp = this.comments.find((item) => item.id == id).replies
				for (let i = 0; i < temp.length; i++) {
					if (temp[i].id == replyId) {
						temp.splice(i, 1)
						break
					}
				}
			} else {
				// 删除一级评论，提交请求到后端

				// 成功后从本地记录中删除该评论
				for (let i = 0; i < this.comments.length; i++) {
					if (this.comments[i].id == id) {
						this.comments.splice(i, 1)
					}
				}
			}
		},
		addComment() {
			if (this.userStatus !== '') {
				if (!this.context) {
					this.$message.warning('评论或留言不能为空哦！')
					return
				} else {
					requests
						.post('/blogs/saveComment', {
							blogId: this.blogId,
							content: this.context
						})
						.then((res) => {
							this.context = ''
							this.commentList()
						})
				}
			} else {
				this.$confirm('此操作需要先登录, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				})
					.then(() => {
						this.$router.push('/login')
					})
					.catch(() => {})
			}
		},
		addReplay(replayId) {
			if (this.userStatus !== '') {
				if (!this.replyContext) {
					this.$message.warning('评论或留言不能为空哦！')
					return
				} else {
					requests
						.post('/blogs/replyComment', {
							blogId: this.blogId,
							parentCommentId: replayId,
							content: this.replyContext
						})
						.then((res) => {
							this.replyContext = ''
							let result = this.commentList()
						})
				}
			} else {
				this.$confirm('此操作需要先登录, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				})
					.then(() => {
						this.$router.push('/login')
					})
					.catch(() => {})
			}
		},
		async commentList() {
			let bolgComment = await reqABlogCommentList(this.blogId)
			console.log(bolgComment)
			this.bolgComment = bolgComment.data

			this.comments = bolgComment.data

			if (bolgComment) {
				this.$message.success('评论成功！')
			}
		}
	},
	computed: {
		...mapState({
			userName: (state) => {
				return state.login.username
			}
		}),
		...mapState({
			userId: (state) => {
				return state.login.id
			},
			userStatus: (state) => {
				return state.login.status
			}
		})
	},

	async created() {
		console.log('111111111111')
		if (this.status === 0 || this.status === 1 || this.status === 2) {
			let userInfo = await reqUserInfo()
			this.selfAvatarUrl = userInfo.data.img
			// console.log(userInfo)
		} else {
			this.selfAvatarUrl = 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
		}
		let bolgResult = await reqABlogOneList(this.blogId)
		console.log(bolgResult)
		this.AuthorAvatarUrl = bolgResult.data.img
		// console.log(bolgResult.img);
		let bolgComment = await reqABlogCommentList(this.blogId)

		this.bolgInfo = bolgResult.data
		this.bolgComment = bolgComment.data
		// console.log(this.bolgComment)
		this.comments = bolgComment.data

		let likeResult = await reqBlogsIsLike(this.blogId)
		let collectResult = await reqBlogsIsCollect(this.blogId)

		this.blogsIsLike = likeResult.data
		this.blogsIsCollect = collectResult.data
	}
}
</script>

<style lang="less" scoped>
.blog ,.comment{
  // background-color: pink;
  width: 88%;
  margin:40px auto
  // align:center
}

.activ1{
  color: rgb(202, 4, 4);

}
.activ2{
  color: rgb(10, 1, 1);

}
.collectButton {
  background-color: #2f5575;
  color:#ffffff;
  border:1px solid #BBBBBB;
  font-size: 15px;
  border-radius: 2px;
  margin-right: 18px;
  cursor: pointer;

}
.blogMiddle{
  border: 1px solid #a3a7b1;
  padding: 15px
}
.blogBottom{
  padding-top: 15px
}
.comment-header{
  padding-right: 20px;
}
.el-icon-star-off ,.el-icon-trophy{
  cursor: pointer;
}
.blogTop{
margin-top: 20px;

}

.blogContent{
  margin-left: 18px;
}
.comment {
  min-height: 26vh;
  border-radius: 5px;
  margin-top: 2px;
  overflow: hidden;

  .active {
    color: rgb(202, 4, 4);
  }
  .comment-header {
    position: relative;
    height: 60px;
    padding: 10px 20px;
    display: flex;
    align-items: center;

    .input {
      margin-left: 10px;
      margin-right: 20px;
      flex: 1;
      /deep/.el-input__inner:focus {
        border-color: #dcdfe6;
      }
    }
  }

  .comment-body {
    min-height: 70px;
    padding: 10px 20px;
    font-size: 14px;
    .first-comment {
      display: flex;
      .input {
        /deep/.el-input__inner:focus {
          border-color: #dcdfe6;
        }
      }
      i {
        margin-right: 5px;
        margin-left: 1vw;
        cursor: pointer;

        &:nth-child(3) {
          color: rgb(202, 4, 4);
        }
      }

      .content {
        margin-left: 10px;
        position: relative;
        flex: 1;

        & > span {
          font-size: 12px;
          color: rgb(130, 129, 129);
        }

        .comment-right {
          position: absolute;
          right: 0;
          top: 0;
        }

        .reply-comment {
          height: 60px;
          display: flex;
          align-items: center;

          .reply-button {
            margin-left: 20px;
            height: 35px;
          }
        }

        .second-comment {
          display: flex;
          padding: 10px 0 10px 5px;
          border-radius: 20px;
          background: #ffffff;
          .to_reply {
            color: rgb(126, 127, 128);
          }
        }
      }
    }
  }
}
</style>
